//
//  MPBidDefaultTableController.m
//  M800Project
//
//  Created by 姚宗超 on 14/11/6.
//  Copyright (c) 2014年 姚宗超. All rights reserved.
//

#import "MPBidDefaultTableController.h"
#import "MPBidTableCell.h"
#import "MPBidObject.h"
#import "KDTableViewSectionObject.h"
#import "MPDeviceObject.h"
#import "MPWebViewController.h"
#import "MPBidTableViewContainer.h"

@interface MPBidDefaultTableController ()
@property (nonatomic, assign)eMPVisitorSubscribeType visitType;

@end

@implementation MPBidDefaultTableController

- (instancetype)initWithVisitType:(eMPVisitorSubscribeType)type
{
    if (self = [super init]) {
        self.visitType = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.showsPullToRefresh = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self createModel];
}

- (void)createModel
{
    [self.sections removeAllObjects];
    [MPNetworkService fetchHotBidWithDeviceId:[MPDeviceObject sharedInstance].deviceId subscribeType:self.visitType sortType:eMPSortTypeDefault upOrDown:eMPSortDown onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        NSArray* infoArray = (NSArray *)info;
        if (infoArray.count <= 0) {
            [self showEmpty:YES];
        }
        else
        {
            [self showEmpty:NO];
        }
        KDTableViewSectionObject* section = [KDTableViewSectionObject new];
        // 假数据模拟
//        for (int i=0; i<=100; i++) {
//            /*
//             "listId":754853,
//             "title":"短期周转1个月_1409261332",
//             "platform":"红岭创投",
//             "productId":"123456"
//             "yearRate":14.64
//             "repayLimitTime":1,
//             "progress":90,
//             "source":"http://www.my089.com/"
//             */
//            NSMutableDictionary* dic = [NSMutableDictionary new];
//            [dic setObject:@"754853" forKey:@"listId"];
//            [dic setObject:@"短期周转1个月_1409261332" forKey:@"title"];
//            [dic setObject:@"红岭创投" forKey:@"platform"];
//            [dic setObject:@"123456" forKey:@"productId"];
//            [dic setObject:@"14.64" forKey:@"yearRate"];
//            [dic setObject:@"1" forKey:@"repayLimitTime"];
//            [dic setObject:@"15" forKey:@"progress"];
//            [dic setObject:@"http://www.my089.com/" forKey:@"source"];
//            [dic setObject:@"1" forKey:@"isMonth"];
//
//            MPBidObject* bid = [MPBidObject bidWithInfoDic:dic];
//            [section.items addObject:bid];
//        }

        for (NSDictionary* infoDic in infoArray) {
            MPBidObject* bid = [MPBidObject bidWithInfoDic:infoDic];
            [section.items addObject:bid];
        }
        [self.sections addObject:section];
        [self.tableView reloadData];
    }];
}

- (void)refreshModel
{
    [MPNetworkService fetchHotBidWithDeviceId:[MPDeviceObject sharedInstance].deviceId subscribeType:eMPVisitorSubscribeTypeRefresh sortType:eMPSortTypeDefault upOrDown:eMPSortDown onComletion:^(NSInteger errorNum, NSDictionary *info, MPError *errorMsg) {
        [self.tableView.pullToRefreshView stopAnimating];
        if (errorMsg) {
            [[MPRemindHelper sharedInstance] showHudOnView:self.navigationController.view withTitleText:errorMsg.titleForError withDuration:1.0f];
            return ;
        }
        [self.sections removeAllObjects];
        NSArray* infoArray = (NSArray *)info;
        if (infoArray.count <= 0) {
            [self showEmpty:YES];
        }
        else
        {
            [self showEmpty:NO];
        }
        KDTableViewSectionObject* section = [KDTableViewSectionObject new];
        // 假数据模拟
//        for (int i=0; i<=100; i++) {
//            /*
//             "listId":754853,
//             "title":"短期周转1个月_1409261332",
//             "platform":"红岭创投",
//             "productId":"123456"
//             "yearRate":14.64
//             "repayLimitTime":1,
//             "progress":90,
//             "source":"http://www.my089.com/"
//             */
//            NSMutableDictionary* dic = [NSMutableDictionary new];
//            [dic setObject:@"754853" forKey:@"listId"];
//            [dic setObject:@"短期周转1个月_1409261332" forKey:@"title"];
//            [dic setObject:@"红岭创投" forKey:@"platform"];
//            [dic setObject:@"123456" forKey:@"productId"];
//            [dic setObject:@"14.64" forKey:@"yearRate"];
//            [dic setObject:@"1" forKey:@"repayLimitTime"];
//            [dic setObject:@"90" forKey:@"progress"];
//            [dic setObject:@"http://www.my089.com/" forKey:@"source"];
//            [dic setObject:@"1" forKey:@"isMonth"];
//            
//            MPBidObject* bid = [MPBidObject bidWithInfoDic:dic];
//            [section.items addObject:bid];
//        }

        for (NSDictionary* infoDic in infoArray) {
            MPBidObject* bid = [MPBidObject bidWithInfoDic:infoDic];
            [section.items addObject:bid];
        }
        [self.sections addObject:section];
        [self.tableView reloadData];
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - protocol
// 注册cell的类型，子类实现
- (void)registerCellClass
{
    NSString* path = [[NSBundle mainBundle] pathForResource:[MPBidTableCell className] ofType:@"nib"];
    if ([NSString stringIsEmpty:path]) {
        [self.tableView registerClass:[MPBidTableCell class] forCellReuseIdentifier:[MPBidTableCell className]];
    }
    else
    {
        UINib* nib = [UINib nibWithNibName:[MPBidTableCell className] bundle:nil];
        [self.tableView registerNib:nib forCellReuseIdentifier:[MPBidTableCell className]];
    }
}

// 从object获取cell的类名
- (Class)cellClassByObject:(id)object
{
    if ([object isKindOfClass:[MPBidObject class]]) {
        return [MPBidTableCell class];
    }
    return nil;
}

// 下拉刷新
- (void)pullToRefreshAction
{
    if (self.delegate) {
        [self.delegate pullRefreshDidStartWithViewController:self];
    }
    [self refreshModel];
}

- (void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        MPBidObject* item = [self objectAtIndexPath:indexPath];
        if (![NSString stringIsEmpty:item.bidIdInFP]) {
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:kMPFirstP2PUrlScheme]])
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kMPFirstP2PUrlScheme]];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
                                                                message:[NSString stringWithFormat:@"No custom URL defined for %@", kMPFirstP2PUrlScheme]
                                                               delegate:self cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        else
        {
            MPWebViewController* vc = [[MPWebViewController alloc] initWithTitle:item.bidName url:item.bidSource];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark -
- (NSString *)viewControllerTitle
{
    return self.viewTitle ? self.viewTitle : self.title;
}

- (void)segmentBtnDidPressed:(BOOL)isDesc
{
    KDLogTrace();
}

@end
